//
//  TCMeetViewController.swift
//  onemeetingmac
//
//  Created by 张衡 on 2019/12/17.
//  Copyright © 2019 onemeeting. All rights reserved.
//

import Foundation

class TCMeetViewController: BaseTRTCViewController {
    
    var timer:Timer?
    var upMenu:NSMenu?
    var isGirdMode:Bool          = true
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.sdkAuto()
        self.setupUI()
        self.enterRoom()
        self.loadData()
        /*
        self.timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(autoSendBarrage), userInfo: nil, repeats: true)
        RunLoop.current.add(self.timer!, forMode: RunLoop.Mode.common)
        */
    }
    
    override func viewDidDisappear() {
        super.viewDidDisappear()
        //弹幕停止
        self.renderer.stop()
        
        if self.timer != nil {
            self.timer?.invalidate()
            self.timer = nil
        }
    }
    
    deinit {
        if self.timer != nil {
            self.timer?.invalidate()
            self.timer = nil
        }
        NotificationCenter.default.removeObserver(self)
    }
    
    
    override func viewWillAppear() {
        super.viewWillAppear()
        self.title = "会议号："+(Td.sh().params.roomId ?? "00000000")
        
        //弹幕
        NotificationCenter.default.addObserver(self,selector: #selector(receiveBarrge(not:)),name:  MTReviBarrgeNotification,object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(rtmpLive(not:)), name: MTLIVENotification, object: nil)
        
        //共享流接受
        NotificationCenter.default.addObserver(self, selector: #selector(reiveSubSteam(not:)), name: MTSubStreamNotification, object: nil)
    }
    
    lazy var renderer: BarrageRenderer = {
        let renderer = BarrageRenderer.init()
        renderer.start()
        return renderer
    }()
    
    lazy var handUpView: HandUpTipView = {
        let view = HandUpTipView()
        view.isHidden = true
        return view
    }()
    
    lazy var fullView: KIcon = {
        let view = KIcon.init(data: KIconGroup.init(title: "", image: "icon_meeting_full"))
        view.imagePosition = .left
        view.wantsLayer = true
        view.layer?.backgroundColor = color_gray(30).withAlphaComponent(0.7).cgColor
        view.layer?.cornerRadius = 3
        view.layer?.masksToBounds = true
        view.tap = { view in
            self.renderer.start()
            self.fullScreenAction(senber: view as? KIcon)
        }
        return view
    }()
    
    lazy var pic2picView: KIcon = {
        let view = KIcon.init(data: KIconGroup.init(title: "分屏模式", image: "icon_meeting_pic2pic"))
        view.imagePosition = .left
        view.wantsLayer = true
        view.layer?.backgroundColor = color_gray(30).withAlphaComponent(0.7).cgColor
        view.layer?.cornerRadius = 3
        view.layer?.masksToBounds = true
        view.isHidden = true
        view.tap = { view in
            TCGirdRender.shared().renderer.enterPic2pic()
            self.reloadpic2picViewStatus()
        }
        return view
    }()
    
    lazy var reloadView: KIcon = {
        let view = KIcon.init(data: KIconGroup.init(title: "", image: "icon_back_home"))
        view.imagePosition = .left
        view.wantsLayer = true
        view.layer?.backgroundColor = color_gray(30).withAlphaComponent(0.7).cgColor
        view.layer?.cornerRadius = 3
        view.layer?.masksToBounds = true
        view.tap = { view in
            TCGirdRender.shared().renderer.reloadData(noLocal:true)
            TCGirdRender.shared().renderer.swapt(focusId: Td.sh().cloud.focusId)
        }
        return view
    }()
    
    lazy var modeView: KIcon = {
        let view = KIcon.init(data: KIconGroup.init(title: "焦点模式", image: "icon_meeting_speaker"))
        view.isHidden = true
        view.imagePosition = .left
        view.wantsLayer = true
        view.layer?.backgroundColor = color_gray(30).withAlphaComponent(0.7).cgColor
        view.layer?.cornerRadius = 3
        view.layer?.masksToBounds = true
        view.tap = { kView in
            if let sView = kView as? KIcon {
                self.swipe(n: sView)
            }
        }
        return view
    }()
    
    lazy var lmARkView: ZHButton = {
        let btn = ZHButton.init()
        btn.normalImage = NSImage.image(name: "icon_hudong") ?? NSImage.init()
        btn.hasBorder = true
        btn.zh_cornerRadius = 3
        btn.zh_backgroundColor = color_gray(30,alpha: 0.7)
        btn.target = self
        btn.action = #selector(inviteButtomAction(sender:))
        return btn
    }()
    
    lazy var inviteButtom: ZHButton = {
        let btn = ZHButton.init()
        btn.normalImage = NSImage.image(name: "icon_meeting_invite") ?? NSImage.init()
        btn.hasBorder = true
        btn.zh_cornerRadius = 3
        btn.zh_backgroundColor = color_gray(30,alpha: 0.7)
        btn.isHidden = true
        btn.target = self
        btn.action = #selector(inviteButtomAction(sender:))
        return btn
    }()
    
    lazy var messageBtn: ZHButton = {
        let btn = ZHButton()
        btn.zh_title = "0 人举手"
        btn.zh_font = NSFont.systemFont(ofSize: 20)
        btn.zh_color = color_gray(255)
        btn.hasBorder = true
        btn.zh_cornerRadius = 20
        btn.zh_backgroundColor = color_main140
        btn.isHidden = true
        btn.target = self
        btn.action = #selector(messageBtnAction(senber:))
        return btn
    }()
    
    
    func loadData() {
        self.girdSetup()
        self.liveV.isHidden = !TXLiteManager.shared().isLiving
        self.liveV.statusRtmp = TXLiteManager.shared().isLiving ? .living:.inloading
    }
    
    func girdSetup() {
        var dataList = Td.sh().usr.remote
        dataList.insert(Td.sh().lc, at: 0)
        TCGirdRender.shared().setup(dataList: dataList)
        TCGirdRender.shared().addNot()
    }
    
    
    func sdkAuto() {
        TXLiteManager.shared().sdkAuto()
        TRTCCloud.sharedInstance().delegate = TrtcCmd.shared
        //TRTCCloud.sharedInstance()?.setAudioFrameDelegate(TrtcCmd.shared)
    }
    
    func enterRoom() {
        TXLiteManager.shared().enterRoom(param: self.params, scene: TRTCAppScene.videoCall)
        IMcmd.shared.modifyName(name: Td.sh().lc.nickName)
    }
    
    
    lazy var params: TParams = {
        let params = TParams()
        params.sdkAppId = UInt32(kTencent_appKey)//UInt32(Td.sh().params.sdkAppId) ??
        params.userId   = Td.sh().params.userId!
        params.roomId   = UInt32(Td.sh().params.roomId!)!
        params.userSig  = Td.sh().params.userSig!
        return params
    }()
    
    
    lazy var tabarView: TCMeetTabar = {
        let view = TCMeetTabar.init(isJoin:Td.sh().isJoin)
        return view
    }()
  
    lazy var liveV: RTMPView = {
        let view = RTMPView.init(frame: NSRect.zero)
        view.tap = { lview in
            self.listAction(senber: lview)
        }
        view.isHidden = true
        return view
    }()
    
    
    func setupUI()  {
        
        self.view.wantsLayer = true
        self.view.layer?.backgroundColor = NSColor.black.cgColor
        
        self.view.addSubview(TCGirdRender.shared().renderer)
        TCGirdRender.shared().renderer.snp.makeConstraints { (make) in
            make.width.centerX.equalToSuperview()
            make.top.equalToSuperview()
            make.height.equalToSuperview().offset(-kTRTCTabarHeight)
        }
        
        self.view.addSubview(renderer.view)
        renderer.view.snp.makeConstraints { (make) in
            make.edges.equalTo(TCGirdRender.shared().renderer)
        }
        
        self.view.addSubview(tabarView)
        tabarView.snp.makeConstraints { (make) in
            make.height.equalTo(kTRTCTabarHeight)
            make.bottom.equalToSuperview()
            make.width.centerX.equalToSuperview()
        }
        
        
        self.view.addSubview(liveV)
        liveV.snp.makeConstraints { (make) in
            make.width.equalTo(170)
            make.height.equalTo(26)
            make.left.equalTo(50)
            make.top.equalTo(10)
        }
        
        self.view.addSubview(fullView)
        fullView.snp.makeConstraints { (make) in
            make.height.equalTo(30)
            make.right.equalTo(-10)
            make.top.equalTo(10)
            make.width.equalTo(30)
        }
        
        self.view.addSubview(reloadView)
        reloadView.snp.makeConstraints { (make) in
            make.height.equalTo(30)
            make.right.equalTo(fullView.snp.left).offset(-10)
            make.top.equalTo(10)
            make.width.equalTo(30)
        }
        
        self.view.addSubview(pic2picView)
        pic2picView.snp.makeConstraints { (make) in
            make.height.equalTo(30)
            make.right.equalTo(reloadView.snp.left).offset(-10)
            make.top.equalTo(10)
            make.width.equalTo(80)
        }
        
        self.view.addSubview(modeView)
        modeView.snp.makeConstraints { (make) in
            make.height.equalTo(30)
            make.right.equalTo(reloadView.snp.left).offset(-10)
            make.top.equalTo(10)
            make.width.equalTo(80)
        }
        
        self.view.addSubview(lmARkView)
        lmARkView.snp.makeConstraints { (make) in
            make.height.equalTo(30)
            make.width.equalTo(30)
            make.left.equalTo(10)
            make.top.equalTo(10)
        }
        
        self.view.addSubview(inviteButtom)
        inviteButtom.snp.makeConstraints { (make) in
            make.height.equalTo(30)
            make.width.equalTo(30)
            make.left.equalTo(lmARkView.snp.right).offset(5)
            make.top.equalTo(10)
        }
        
        
        self.view.addSubview(handUpView)
        handUpView.snp.makeConstraints { (make) in
            make.width.equalTo(160)
            make.height.equalTo(40)
            make.bottom.equalTo(-70)
            make.centerX.equalTo(tabarView.centerSubView[1])
        }
        
        self.view.addSubview(messageBtn)
        messageBtn.snp.makeConstraints { (make) in
            make.height.equalTo(40)
            make.width.equalTo(120)
            make.left.equalTo(20)
            make.bottom.equalTo(-80)
        }
        
    }
    
}

//MARK:- 通知
extension TCMeetViewController {
    func reloadpic2picViewStatus() {
        let isPic2pic = TCGirdRender.shared().renderer.isPic2pic
        let title = isPic2pic ? "单屏模式":"分屏模式"
        let imageString = isPic2pic ? "icon_meeting_pic1pic":"icon_meeting_pic2pic"
        self.pic2picView.upText = title
        self.pic2picView.imageV.image = NSImage.image(name:imageString)
    }
    
    @objc func reiveSubSteam(not:Notification) {
        guard let mode = not.object as? StreamMode else {
            return
        }
        self.pic2picView.isHidden = !mode.available
        self.reloadpic2picViewStatus()
    }
    
    @objc func rtmpLive(not:Notification) {
        guard let string = not.object as? String else { return }
        if string == ReloadNotification {
            if let subView = self.tabarView.centerSubView[safe:5] {
                let image = TXLiteManager.shared().isLiving ? "toolbar_rtmp_stop":"toolbar_rtmp_start"
                subView.icon.image = NSImage.image(name:image)
                let type = TXLiteManager.shared().pushType == .live ? "直播":"录制"
                let title = TXLiteManager.shared().isLiving ? "停止\(type)":"开启\(type)"
                subView.title.stringValue = title
            }
            
            
            self.liveV.isHidden = !TXLiteManager.shared().isLiving
            if TXLiteManager.shared().isLiving {
                self.liveV.statusRtmp = .inloading
                RtcEngine.getRtmp(type: TXLiteManager.shared().pushType) { (result) in
                    let mode = RtmpMode.deserialize(from: result)
                    Td.sh().live.rtmpurl = mode?.rtmpurl
                    Td.sh().live.liveurl = mode?.liveurl
                    if let rtmpurl = mode?.rtmpurl {
                        TXLiteManager.shared().startPublishCDNStream(url: rtmpurl)
                        self.liveV.statusRtmp = .living
                        TXLiteManager.needAfterPushMix()
                    }
                }
            }else {
                self.liveV.statusRtmp = .default
                TXLiteManager.shared().stopPublishCDNStream()
            }
        }
        
    }
    @objc func receiveBarrge(not:Notification)  {
        guard let descriptor = not.object as? BarrageDescriptor else {
            return
        }
        self.renderer.receive(descriptor)
    }
    
    func enterFullScreen() {
        self.tabarView.isHidden = true
        TCGirdRender.shared().renderer.snp.updateConstraints { (make) in
            make.height.equalToSuperview()
        }
        
        MTNot.postHasUser(isok: false)
        self.fullView.upText = "退出全屏"
        TCGirdRender.shared().renderer.isFullScreen = true
        if TCGirdRender.shared().renderer.mode == .speaker {
            TrtcEngine.standOrderFront(inWindow: self.view.window)
        }
    }
    
    func exitFullScreen() {
        self.tabarView.isHidden = false
        TCGirdRender.shared().renderer.snp.updateConstraints { (make) in
            make.height.equalToSuperview().offset(-kTRTCTabarHeight)
        }
        
        self.fullView.upText = ""
        TCGirdRender.shared().renderer.isFullScreen = false
        if TCGirdRender.shared().renderer.mode == .speaker {
            TrtcEngine.standClose()
            TCGirdRender.shared().renderer.reloadData(noLocal: true)
        }
    }
    
    
    func fullScreenAction(senber:KIcon?) {
        //self.view.window?.zoom(self)
        self.view.window?.toggleFullScreen(self)
        //self.view.isInFullScreenMode ? self.view.exitFullScreen():self.view.enterFullScreen()
        //NSApplication.shared.currentSystemPresentationOptions == .fullScreen
        
    }
    
    @objc func inviteButtomAction(sender:ZHButton) {
        let window = NSWindow.init(contentViewController: ShareViewController.init(appearance: DSAppearance.dark))
        window.lorderFront(nil)
        let yellowPoint = NSPoint(x: sender.frame.width+5, y: window.frame.height)
        let pointInWindow = sender.convert(yellowPoint, to: nil)
        let pointOnScreen = sender.window?.convertToScreen(NSRect.init(origin: pointInWindow, size: CGSize.zero)).origin ?? .zero
        window.setFrameOrigin(pointOnScreen)
    }
    
    func livePopAction(indx:Int)  {
        switch indx {
        case 0:
            TXLiteManager.shared().isLiving = false
            MTNot.postRTMPLive()
        case 1:
            if !Td.sh().cloud.hasLive {
                show_msg("没有关联直播")
                return
            }
            
            guard let liveurl = Td.sh().live.liveurl else {
                return
            }
            if liveurl != "" {
                NSPasteboard.general.declareTypes([NSPasteboard.PasteboardType.string], owner: nil)
                NSPasteboard.general.setString(liveurl, forType: NSPasteboard.PasteboardType.string)
                show_msg("复制成功")
            }
            
        case 2:
            if !Td.sh().cloud.hasLive {
                show_msg("没有关联直播")
                return
            }
            
            guard let liveurl = Td.sh().live.liveurl else {
                return
            }
            if let url = URL(string:liveurl) {
                NSWorkspace.shared.open(url)
            }
            
        default:
            break
        }
    }
    
    /*
    @objc func liveViewAction(senber:RTMPView?) {
        if senber?.statusRtmp == .living {
            let menuVc = ZMenuViewController()
            menuVc.indxTap = { indx in
                Lk.shared.dismiss()
                self.livePopAction(indx: indx)
            }
            let text = TXLiteManager.shared().isLiving ?  "停止直播推流":"开始直播推流"
            menuVc.dataList = [text,"复制地址","观看直播"]
             
            let lk = Lk.create(controller: menuVc)
            lk.show(relativeTo: (senber!.frame), of: senber!, preferredEdge: NSRectEdge.maxY)
        }
    }
    */
    
    
    func listAction(senber:NSView)  {
        let menu = NSMenu.init()
        menu.isDark = true
        self.createItems().forEach { (item) in
            menu.addItem(item)
        }
        menu.needsUpdate()
        self.upMenu = menu
        let p = NSPoint(x: 40, y: -6)
        menu.popUp(positioning: nil, at: p, in: senber)
    }
    
    func createItems() -> [NSMenuItem] {
        var item:[NSMenuItem] = []
        let type = Td.sh().cloud.hasLive ? "直播":"录制"
        let text = TXLiteManager.shared().isLiving ?  "停止\(type)推流":"开始\(type)推流"
        var menuNames:[String] = [text]
        if TXLiteManager.shared().pushType == .live {
            menuNames.append("复制链接")
            menuNames.append("观看\(type)")
        }
        
        for (inx,val) in menuNames.enumerated() {
            let menu = NSMenuItem.init(title: val, action: #selector(liveMenuAction(senber:)), keyEquivalent: "")
            menu.tag = inx
            menu.state = .off
            menu.target = self
            item.append(menu)
            
            item.append(NSMenuItem.separator())
        }
        return item
    }
    
    @objc func liveMenuAction(senber:NSMenuItem) {
        self.upMenu?.cancelTracking()
        self.livePopAction(indx: senber.tag)
    }
    
    @objc func messageBtnAction(senber:ZHButton) {
        let controller = MessageHandViewController()
        let popover = NSPopover.create(controller: controller)
        popover.show(senber, preferredEdge: NSRectEdge.maxY)
    }
    
    func readHasHands() {
        let count = Td.hands.count
        if count > 0 {
            //self.messageBtn.isHidden = false
            self.messageBtn.zh_title = "\(count)"+" 人举手"
        }else {
            self.messageBtn.isHidden = true
        }
    }
    
    func swipe(n:KIcon) {
        if Td.fullScreen == true {
            show_msg("全屏状态下不允许切换")
            return
        }
        self.isGirdMode = !self.isGirdMode
        let girdData = KIconGroup.init(title: "画廊模式", image: "icon_meeting_gird")
        let focusData = KIconGroup.init(title: "焦点模式", image: "icon_meeting_speaker")
        let data = self.isGirdMode ? focusData:girdData
        n.setData(newData: data)
        if self.isGirdMode == true {
            TCGirdRender.shared().renderer.mode = .gird
        }else {
            TCGirdRender.shared().renderer.mode = .speaker
        }
        TCGirdRender.shared().renderer.reloadMode()
    }
    
}




extension TCMeetViewController {
    func walkTextSpriteDescriptorWithDirection(direction:Int) -> BarrageDescriptor{
        let descriptor = BarrageDescriptor.init()
        descriptor.spriteName = BarrageWalkTextSprite.className()
        descriptor.params["text"] = "我是弹幕。"
        descriptor.params["textColor"] = color_random_rgba()
        descriptor.params["speed"] = (100*Double(arc4random())/Double(RAND_MAX)+50)
        descriptor.params["direction"] = Int(direction)
        return descriptor
    }
    
    func createDanmukuWithDict(dict:[String:Any]) -> BarrageDescriptor? {
        guard let pString = dict["p"] as? String,let mString = dict["m"] as? String else {
            return nil
        }
        if pString.count<0 || mString.count<0 {
            return nil
        }
        
        let pArray = pString.components(separatedBy: ",")
        if pArray.count < 5 {
            return nil
        }
        let descriptor = BarrageDescriptor()
        descriptor.spriteName = BarrageWalkTextSprite.className()
        descriptor.params["direction"] = Int(pArray[1])!%3
        descriptor.params["timestamp"] = Float(pArray[0])!/1000.0
        descriptor.params["text"] = mString
        descriptor.params["speed"] = (100*Double(arc4random())/Double(RAND_MAX)+50)
        descriptor.params["textColor"] = color_random_rgba()
        return descriptor
    }
    
    @objc func autoSendBarrage()  {
        self.renderer.receive(self.walkTextSpriteDescriptorWithDirection(direction: Int(BarrageWalkDirection.R2L.rawValue)))
    }
}
